package com.jxc.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.jxc.service.BillServiceImpl;
import com.jxc.utils.DateUtils;
import com.jxc.utils.excel.JxlsUtils;
import com.jxc.vo.Response;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class BillController {
	
	@Autowired
	private BillServiceImpl billServiceImpl;
	
	@PostMapping("/buildBill")
	public Response<Object> buildBill(@RequestBody String json) {
		billServiceImpl.save(JSONObject.parseObject(json));
		return Response.getSuccess();
	}
	
	@PostMapping("/queryBill")
	public Response<?> queryBill(@RequestBody String json) {
		return Response.getResult(billServiceImpl.query(json));
	}
	
	@PostMapping("/queryBillDetail")
	public Response<?> queryBillDetail(@RequestBody String json) {
		return Response.getResult(billServiceImpl.queryBillDetail(json));
	}
	
	@PostMapping("/saveBillCustomer")
	public Response<?> saveBillCustomer(@RequestBody String json) {
		return Response.getResult(billServiceImpl.saveBillCustomer(json));
	}
	
	@PostMapping("/queryCustomerList")
	public Response<?> queryCustomerList(@RequestBody String json) {
		return Response.getResult(billServiceImpl.queryCustomerList(json));
	}
	
	@PostMapping("/queryCompanyList")
	public Response<?> queryCompanyList(@RequestBody String json) {
		return Response.getResult(billServiceImpl.queryCompanyList(json));
	}
	
	@PostMapping("/customerTransaction")
	public Response<?> customerTransaction(@RequestBody String json) {
		return Response.getResult(billServiceImpl.customerTransaction(json));
	}
	
	@PostMapping("/buildBillStatement")
	public Response<Object> buildBillStatement(@RequestBody String json) {
		try {
			JSONObject request = JSONObject.parseObject(json);
			File dir = new File(ResourceUtils.getURL("classpath:").getPath());
			String jarParent = dir.getParentFile().getParentFile().getParentFile().getPath().replace("file:", "");
			String fileName = "/tmp/"+request.getString("company")+"_"+DateUtils.format(new Date(), "yyyyMMddHHmmss")+".xls";
			File tmp = new File(jarParent+fileName);
			if(!tmp.exists()) {
				if(!tmp.getParentFile().exists()) {
					tmp.getParentFile().mkdirs();
				}
				log.info(tmp.getPath());
				tmp.createNewFile();
			}
			JxlsUtils.exportExcel(ResourceUtils.getURL("classpath:config/template.xls").openStream(),new FileOutputStream(tmp) , billServiceImpl.buildBillStatement(request));
			return Response.getResult(fileName);
		} catch (IOException e) {
			log.error("导出excel异常",e);
			return Response.getError(e.getMessage());
		}
	}
}
